package com.dream.wuliu.view;

import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ItemSelect;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.WindowFeature;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.widget.ArrayAdapter;
import android.widget.ScrollView;
import android.widget.Spinner;

import com.actionbarsherlock.view.Window;
import com.beardedhen.androidbootstrap.BootstrapButton;
import com.beardedhen.androidbootstrap.BootstrapEditText;
import com.dream.vo.api.ApiOrderDetail;
import com.dream.vo.api.ApiOrderUpdate;
import com.dream.vo.api.ApiResult;
import com.dream.vo.api.ApiSpinnerData;
import com.dream.vo.api.SpinnerItem;
import com.dream.wuliu.base.AppConstants;
import com.dream.wuliu.service.MasterService;
import com.dream.wuliu.service.OrderService;
import com.dream.wuliu.service.ServiceFactory;
import com.dream.wuliu.utils.GsonHelper;
import com.dream.wuliu.utils.MyDatePicker;
import com.dream.wuliu.utils.MyUtils;
import com.dream.wuliu.utils.ServiceBuilder;
import com.google.zxing.client.android.CaptureActivity;
import com.google.zxing.client.android.Intents;
@EActivity(R.layout.order_update)
@WindowFeature({(int)Window.FEATURE_INDETERMINATE_PROGRESS })
public class OrderUpdateActivity extends BaseActivity {
	
	@Bean
	ServiceBuilder appServiceHelper;
	
	@Extra("detail")
	String detail;
	
	@ViewById(R.id.spFirstCat)
	Spinner spFirstCat;
	
	@ViewById(R.id.spSecondCat)
	Spinner spSecondCat;
	
	@ViewById(R.id.tvProName)
	BootstrapEditText tvProName;
	
	@ViewById(R.id.tvProPuchaseDate)
	BootstrapEditText tvProPuchaseDate;
	
	@ViewById(R.id.tvProBarcode)
	BootstrapEditText tvProBarcode;
	
	@ViewById(R.id.tvProRecepitNo)
	BootstrapEditText tvProRecepitNo;
	
	@ViewById(R.id.tvProMandatoryNo)
	BootstrapEditText tvProMandatoryNo;
	
	@ViewById(R.id.svContent)
	ScrollView svContent;
	
	@ViewById(R.id.btnUpdate)
	BootstrapButton btnUpdate;
	
	ApiOrderDetail orderDetail = null;
	
	private ApiOrderUpdate orderUpdate = new ApiOrderUpdate();
	
    @AfterViews  
    public void init(){
    	
    	btnUpdate.setFocusable(true);
    	btnUpdate.requestFocus();
    	btnUpdate.setFocusableInTouchMode(true);
    	
    	svContent.smoothScrollTo(0,0);
    	showProgress();
    	getProductCategory();
    }  
    
    @Background
    public void getProductCategory(){
    	
    	orderDetail = GsonHelper.orderDetail(detail);
    	if(orderDetail == null){ return ;}
    	
    	String gson = myPrefs.productCategory().get();
    	if(MyUtils.isBlank(gson)){
    		gson = new ServiceFactory.MasterServiceHelper() {
				
				@Override
				public ApiResult doService(MasterService service) {
					return service.category();
				}
			}.execute(this);
        	myPrefs.productCategory().put(gson);
    	}
    	
    	List<ApiSpinnerData> productCategory = GsonHelper.productCategory(gson);
     	List<SpinnerItem> first = MyUtils.newArrayList();
     	if(MyUtils.isNotEmpty(productCategory)){
     		for(ApiSpinnerData data : productCategory){
     			first.add(data.getFrist());
     			break;
     		} 
     	}
    	setData(first,orderDetail);
    }
    
    @UiThread
    public void setData(List<SpinnerItem> first,ApiOrderDetail orderDetail){
    	hideProgress();
    	ArrayAdapter<SpinnerItem> firstAdapter = new ArrayAdapter<SpinnerItem>(this, android.R.layout.simple_list_item_single_choice, first);
    	spFirstCat.setAdapter(firstAdapter);
    	
    	if(MyUtils.isNotBlank(orderDetail.getProFirstCatCode())){
	    	SpinnerItem selectedItem = new SpinnerItem();
	    	selectedItem.setCode(orderDetail.getProFirstCatCode());
	    	int selected = first.indexOf(selectedItem);
	    	if(selected > -1)
	    		spFirstCat.setSelection(selected);
    	}
    	
    	tvProName.setText(orderDetail.getProName());
    	tvProPuchaseDate.setText(orderDetail.getProPurchaseDate());
    	tvProBarcode.setText(orderDetail.getProBarcode());
    	tvProRecepitNo.setText(orderDetail.getProRecepitNo());
    	tvProMandatoryNo.setText(orderDetail.getProMandatoryNo());
    	
    	orderUpdate.setId(orderDetail.getId());
    }
    
    @ItemSelect(R.id.spFirstCat)
    public void firstCatChange(boolean selected,SpinnerItem item ){
    	
    	if(!selected){return ;}
    	String gson = myPrefs.productCategory().get();
    	List<ApiSpinnerData> productCategory = GsonHelper.productCategory(gson);
    	List<SpinnerItem> second = MyUtils.newArrayList();
    	if(MyUtils.isNotEmpty(productCategory)){
     		for(ApiSpinnerData data : productCategory){
     			if(data.getFrist().getCode().equals(item.getCode())){
     				second = data.getSecond();
     				break;
     			}
     		}
     	}
    	ArrayAdapter<SpinnerItem> secondAdapter = new ArrayAdapter<SpinnerItem>(this, android.R.layout.simple_list_item_single_choice, second);
    	spSecondCat.setAdapter(secondAdapter);
    	
    	if(MyUtils.isNotBlank(orderDetail.getProSecondCatCode())){
	    	SpinnerItem selectedItem = new SpinnerItem();
	    	selectedItem.setCode(orderDetail.getProSecondCatCode());
	    	int index = second.indexOf(selectedItem);
	    	if(index > -1)
	    		spSecondCat.setSelection(index);
    	}
    }
    
    @Click(R.id.btnScanBarcode)
    public void barcodeScan(){
    	doZXing();
    }
    
    @Click(R.id.btnDate)
    public void btnDate(){
    	MyDatePicker.createDialog(this,tvProPuchaseDate);
    }
    
    private static final int REQUEST_CODE = 200;
	private void doZXing() {
		
        Intent intent = new Intent();
        intent.setAction(Intents.Scan.ACTION);
        intent.putExtra(Intents.Scan.CHARACTER_SET, AppConstants.ENCODE_UTF_8);
        intent.putExtra(Intents.Scan.WIDTH, 600);
        intent.putExtra(Intents.Scan.HEIGHT, 400);
        intent.setClass(this, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_CODE);
        
    }
	
	 @OnActivityResult(REQUEST_CODE)
	 void onResult(int resultCode, Intent intent) {
	        if (intent != null && resultCode == Activity.RESULT_OK) {
	        	tvProBarcode.setText(intent.getStringExtra(Intents.Scan.RESULT));
	        }
	 }
	 
	 @Click(R.id.btnUpdate)
	 public void btnUpdate(){
		    if(orderUpdate.getId() != null){
		    	
		    	SpinnerItem first = (SpinnerItem)spFirstCat.getSelectedItem();
		    	SpinnerItem second = (SpinnerItem)spSecondCat.getSelectedItem();
		    	
		    	orderUpdate.setProBarcode(tvProBarcode.getText().toString());
		    	orderUpdate.setProFirstCatCode(first.getCode());
		    	orderUpdate.setProMandatoryNo(tvProMandatoryNo.getText().toString());
		    	orderUpdate.setProName(tvProName.getText().toString());
		    	orderUpdate.setProPurchaseDate(tvProPuchaseDate.getText().toString());
		    	orderUpdate.setProRecepitNo(tvProRecepitNo.getText().toString());
		    	orderUpdate.setProSecondCatCode(second.getCode());
		    	ProgressDialog dialog = showDialogProgress();
		    	update(orderUpdate,dialog);
		    }
		 
	 }
	 
	 @Background
	 public void update(final ApiOrderUpdate order,ProgressDialog dialog){
		 
		 String msg = new ServiceFactory.OrderServiceHelper() {
				@Override
				public ApiResult doService(OrderService service) {
					return service.update(order.toGson());
				}
				
		}.execute(this);
		updateCallback(msg,dialog);
	 }
	 
	 @UiThread
	 public void updateCallback(String msg,ProgressDialog dialog){
		 dialog.dismiss();
		 if(AppConstants.STR_TRUE.equals(msg)){
			 this.finish();
			 PortalActivity_.intent(this).start();
		 }
		 
	 }
}

